package com.cangchu.ui.fragment;

import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
import com.cangchu.R;
import com.cangchu.db.domain.Batch;
import com.cangchu.util.GsonUtil;
import com.cangchu.util.HttpUtils;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import cz.msebera.android.httpclient.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 批次清单列表，使用post请求版本，如果与本地保存的版本不一致
 * 提醒用户点击按钮进行更新【为了实现两个fragment管理，特意做成不自动】
 * Created by 张博文 on 2016/9/29.
 */
public class BatchListFragment extends ListFragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        Log.d("BatchListFragment", "内容刷新");
        initBatchInfo();

        return view;
    }

    private void initBatchInfo() {
        final List<Map<String, Object>> listitem = new ArrayList<>();
        HttpUtils.post(getActivity(), "http://121.43.189.138:6000/batch", new RequestParams("version", "1"), new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    JSONArray list = response.getJSONArray("data");
                    List<Batch> listObj = GsonUtil.toEntity(list.toString(), new TypeToken<List<Batch>>() {
                    });
                    for (Batch batch : listObj) {
                        Map map = new HashMap();
                        map.put("code", batch.getCode());
                        map.put("info", batch.getInfo());
                        listitem.add(map);
                    }
                    SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), listitem, R.layout.fragment_listview, new String[]{"code", "info"},
                            new int[]{R.id.item1, R.id.item2});
                    setListAdapter(simpleAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
